/**
 * 表格模块
 */
layui.define(['jquery', 'form', 'table', 'laydate', 'layer', 'bmsglobal', 'bmsrdm'], function (exports) {
    var $ = layui.$;
    var bmsrdm = layui.bmsrdm;
    var form = layui.form;
    var table = layui.table;
    var layer = layui.layer;
    var MOD_NAME = 'bmstable';

    var tableId = 'BMS-tableId';
    var bmstable = {
        config: {
            elems: {
                formId: 'BMS-tableFormId'// 表格搜索 form 表单 id
                , formClass: 'BMS-tableFormClass'// 表格搜索form表单class
                , formFilter: 'BMS-tableFormFilter'// 表格搜索事件过滤器
                , tableReloadFilter: 'BMS-tableReloadFilter'// 表格重载事件触发按钮
                , tableId: tableId// 表格ID
                , tableFilter: 'BMS-tableFilter'// 表格事件过滤器
                , tableBarId: 'BMS-tableBarId'// 表格工具栏
                , trOperateBar: 'BMS-trOperateBarId'// 行操作栏
                , trStyleStatusId: 'BMS-trStyleStatus'// 行status样式模板ID
                , trStyleIsNavId: 'BMS-trStyleIsNav'// 行isnav样式模板ID
                , tableReloadId: 'BMS-tableReloadId'// 用于表格渲染ID
                , elem: '#' + tableId
                , method: 'post'
                , height: 'full-280'
                , page: true
                , dataUrl: ''
                , editUrl: '-'
                , addUrl: '-'
                , delUrl: '-'
                , statusUrl: '-'
                , dialogSize: ['500px', '500px']
                , request: {
                    pageName: BMS.config.keys.pager.pageNum
                    , limitName: BMS.config.keys.pager.pageSize
                }, response: {
                    statusName: BMS.config.keys.codeName
                    , statusCode: BMS.config.code.succ// 成功状态码
                    , msgName: BMS.config.keys.msgName
                    , countName: BMS.config.keys.pager.totalCount
                    , dataName: BMS.config.keys.dataName
                }
            }
        }
    }

    var call = {
        rdmElemFlags: function (options, prefix) {
            var len = 10;
            options = options || {};
            options = $.extend(bmstable.config.elems, options);// 复制一份
            options.id = options.tableReloadId;

            layui.each(options, function (index, item) {
                if (!index)
                    return;

                if (options[index] == null || options[index] == undefined) {
                    options[index] = bmsrdm.randomStr(prefix + index + '-', len);
                }
            })

            return options;
        }
        , render: function (options) {
            // form元素渲染
            form.render(null);


            /**
             * 主要是在 layui 的基础上增加默认值
             */
            table.render(options);
        }
        /**
         * 监听
         * @param options
         * @param active
         */
        , monitor: function (options, actives) {
            //监听表格重载
            if (options.tableReloadFilter) {
                form.on('submit(' + options.tableReloadFilter + ')', function (data) {
                    // console.log(data.field)
                    // table.reload(tableReloadId, {
                    //     where: data.field
                    // });
                    return false;
                });
            }

            // 复选框
            if (options.tableReloadId && actives.checkbox)
            {
                table.on('checkbox('+options.tableFilter+')', function(data) {
                    actives.checkbox(data);
                })
            }

            // 监听表格工具
            if (options.tableBarId) {
                // 监听表格操作条
                $('#' + options.tableBarId + ' button, .' + options.formClass + ' button').on('click', function () {
                    var layEvent = $(this).attr('lay-event');
                    bmstable.active[layEvent] ? actives[layEvent].call(this) : '';
                });
            }

            //监听行操作条
            if (options.trOperateBar) {
                //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
                table.on('tool(' + options.tableFilter + ')', function (obj) {
                    var data = obj.data; //获得当前行数据
                    var layEvent = obj.event; //获得 lay-event 对应的值
                    var tr = obj.tr; //获得当前行 tr 的DOM对象

                    actives[layEvent] ? actives[layEvent].call(this, obj) : '';
                })
            }
        }
    }

    /**
     * 所有操作
     * @type {{}}
     */
    bmstable.active = function (options) {
        var activeThat = this;
        this.active = {
            reload: function () {
                var where = {};
                // 直接拷贝 layui
                $('.' + options.formClass).find('input,select,textarea').each(function (i, item) {
                    if(!item.name) return;
                    if(/^checkbox|radio$/.test(item.type) && !item.checked) return;
                    where[item.name] = item.value;
                })

                table.reload(options.tableReloadId, {
                    where: where
                });
            }
            , add: function () {
                var dialogIndex = layer.open({
                    title: '新增'
                    , type: 2
                    , closeBtn: 2
                    , content: options.addUrl
                    , area: options.dialogSize
                });
            }
            , del: function (obj) {
                var msg = '确认删除？';
                layer.confirm(msg, function (index) {
                    //向服务端发送指令
                    $.ajax({url: delUrl, type:'delete', data:{id: obj.data.id}, success: function(resp){
                        parent.layui.layer.close(index);
                        activeThat.active.reload();// 手动刷新表格
                    }})
                });
            }
            /**
             * 更新状态
             * @param obj
             * @param status  true 为解锁，false为锁定，同时传入后台的参数也为 true/false
             */
            , _status: function (obj, status) {
                var msg = status ? '确认解锁？' : '确认锁定？';
                layer.confirm(msg, function (index) {
                    //向服务端发送指令
                    $.get(options.statusUrl, {id: obj.data.id, status: status}, function (resp) {
                        parent.layui.layer.close(index);
                        activeThat.active.reload();// 手动刷新表格
                    })
                });
            }
            , lock: function (obj) {
                activeThat.active._status(obj, false);
            }
            , unlock: function (obj) {
                activeThat.active._status(obj, true);
            }
            , edit: function (obj) {
                var editUrlWithId = options.editUrl;
                editUrlWithId += options.editUrl.indexOf("?") > -1 ? '&' : '?';
                editUrlWithId += 'id=' + obj.data.id;
                var dialogIndex = layer.open({
                    title: '编辑'
                    , type: 2
                    , closeBtn: 2
                    , content: editUrlWithId
                    , area: options.dialogSize
                });
            }
        }

        return this.active;
    }

    bmstable.init = function () {
        //call.rdmElemFlags({}, elemsPrefix);

        // 随机生成
    }


    bmstable.init();

    var elemsPrefix = "BMS-";// 元素标识前缀
    bmstable.render = function (options, actives) {
        options = options || {};
        actives = actives || {}
        // 绑定定制的配置
        options = call.rdmElemFlags(options, elemsPrefix);
        // 绑定定制的事件
        actives = $.extend(bmstable.active(options), actives);

        call.render(options);
        call.monitor(options, actives);

        bmstable.reload = actives.reload;
    }


    exports(MOD_NAME, bmstable);
})